package com.weirblog.login;

import com.weirblog.entity.Users;
import com.weirblog.util.JWTUtil;

import io.quarkus.hibernate.reactive.panache.PanacheEntityBase;
import me.zhyd.oauth.config.AuthConfig;
import me.zhyd.oauth.model.AuthCallback;
import me.zhyd.oauth.model.AuthResponse;
import me.zhyd.oauth.model.AuthUser;
import me.zhyd.oauth.request.AuthGiteeRequest;
import me.zhyd.oauth.request.AuthRequest;
import java.util.Date;
import java.util.List;
import java.util.UUID;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.UriBuilder;

/**
 * Shows how to create a simple OAuth integration.
 *
 * To Use:
 *
 * export CLIENT_ID=XXX export CLIENT_SECRET=XXX mvn compile quarkus:dev
 *
 *
 * in browser navigate to http://2a38-223-91-168-157.ngrok.io/oauth/login
 */
@Path("/oauth-gitee")
public class GiteeOauthResource {

	@GET
	@Path("/callback")
	public Response login(
//    		AuthCallback callback
			@QueryParam("state") String state, @QueryParam("code") String code) {
		AuthCallback callback = new AuthCallback();
		callback.setCode(code);
		callback.setState(state);
		AuthRequest authRequest = getAuthRequest();
		authRequest.authorize(state);
		AuthResponse<AuthUser> login = authRequest.login(callback);
//        System.out.println("-----------AuthResponse---------" + login.getData());
		String username = login.getData().getUsername();
		String uuid = login.getData().getUuid();
		String avatar = login.getData().getAvatar();
		List<PanacheEntityBase> users = Users.list("userName=?1 and accountId=?2", username, uuid).await()
				.indefinitely();
		Users u = null;
		if (users != null && users.size() > 0) {
			u = (Users) users.get(0);
		} else {
			u = new Users();
			u.createDate = new Date();
			u.accountId = uuid;
			u.token = UUID.randomUUID().toString();
			u.userName = username;
			u.profileImageUrl = avatar;
			u.persistAndFlush().await().indefinitely();
		}
		String sign = JWTUtil.sign(u.token, u.accountId + "_" + u.userName);
		return Response.seeOther(UriBuilder.fromPath("/bbs").queryParam("sign", sign).build()).build();
	}

	private AuthRequest getAuthRequest() {
		return new AuthGiteeRequest(
				AuthConfig.builder().clientId("68fc089e7110da832d9365c2a40de98210f7f310b1e311a11b8545b0b86c2e7a")
						.clientSecret("fdf188ec69dc529618b95edcc435548d0abdec14a2019ea6b8d929149d375500")
						.redirectUri("http://a881-223-91-168-24.ngrok.io/oauth-gitee/callback").build());
	}

}